import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, Stack, Grid, Menu, MenuItem } from '@mui/material';
import GitHubIcon from '@mui/icons-material/GitHub';
import { useAuth } from 'contexts/AuthContext';
// Import the StyledButton component from our components/objects directory
import StyledButton from 'components/objects/StyledButton';

const Footer = ({ darkMode = false }) => {
  const navigate = useNavigate();
  
  // Get user from auth context with empty object fallback for safety
  const { user = {} } = useAuth();
  
  // Check if user is admin or superadmin
  const isAdmin = user?.role === 'admin' || user?.isAdmin === true || user?.role === 'superadmin';
  
  // For managing dropdown menus
  const [anchorEls, setAnchorEls] = useState({
    publicRoutes: null,
    publicAPIs: null,
    additionalPublicRoutes: null,
    githubLinksAndResources: null,
    authRoutes: null,
    privateRoutes: null
  });

  const handleMenuOpen = (menuName) => (event) => {
    setAnchorEls({ ...anchorEls, [menuName]: event.currentTarget });
  };

  const handleMenuClose = (menuName) => () => {
    setAnchorEls({ ...anchorEls, [menuName]: null });
  };

  const handleMenuItemClick = (path, menuName) => {
    navigateOpen(path);
    handleMenuClose(menuName)();
  };

  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const navigateOpen = (path) => {
    if (path.startsWith('http')) {
      navigatePage(path);
    } else {
      navigate(path);
    }
  };
  
  const publicRoutes = [
    { label: "Return home", path: "/home-page" },
    { label: "Splash page", path: "/" },
    { label: "Getting started", path: "/getting-started" },
    { label: "Adding a card", path: "/add-card" },
    { label: "Login Page", path: "/login-page" },
    { label: "Overview", path: "/overview" },
    { label: "Overview Alt", path: "/overview-alt" }
  ];

  const publicAPIs = [
    { label: "API Endpoints", path: "/api-endpoints" },
    { label: "Experimental APIs", path: "/experimental-apis" },
    { label: "Discover more", path: "/discover-more" },
    { label: "Subscriptions", path: "/subscriptions" },
    { label: "Dashboard Page", path: "/dashboard-page" },
    { label: "Routing libraries", path: "/routing-libraries" },
    { label: "Plans", path: "/plans" }
  ];

  const additionalPublicRoutes = [
    { label: "Dashboard Test", path: "/DashboardTest" },
    { label: "Integrations", path: "/integrations" },
    { label: "Teams Page", path: "/teams-page" },
    { label: "Callbacks", path: "/callbacks" },
    { label: "Stripe sessions", path: "/stripe-sessions" },
    { label: "Templates", path: "/templates" },
    { label: "Webhooks", path: "/webhooks" }
  ];

  const githubLinksAndResources = [
    { 
      label: "Go API", 
      path: "https://github.com/startersaas/startersaas-backend-go-api-main.git",
      icon: <GitHubIcon fontSize="small" />
    },
    { 
      label: "Node API", 
      path: "https://github.com/startersaas/startersaas-backend-node-api-main.git",
      icon: <GitHubIcon fontSize="small" />
    },
    { 
      label: "React API", 
      path: "https://github.com/startersaas/startersaas-frontend-react-spa.git",
      icon: <GitHubIcon fontSize="small" />
    },
    { label: "Cards", path: "/cards" },
    { label: "Payments", path: "/payments" },
    { label: "Trials", path: "/trials" },
    { label: "Subscribers", path: "/subscribers" },
    { label: "Admin", path: "/admin" },
    { label: "Users Page", path: "/users-page" },
    { label: "Usage with webhooks", path: "/webhooks-usage" }
  ];

  const authRoutes = [
    { label: "Login", path: "/auth/login", color: "primary" },
    { label: "Forgot Password", path: "/auth/forgot-password", color: "primary" },
    { label: "Resend Activation", path: "/auth/resend-activation", color: "primary" },
    { label: "Reset Password", path: "/auth/reset-password/:email", color: "primary" },
    { label: "Activate Account", path: "/auth/activate/:email", color: "primary" },
    { label: "Register", path: "/auth/register", color: "primary" }
  ];

  const privateRoutes = [
    { label: "Dashboard", path: "/dashboard", color: "secondary" },
    { label: "Teams", path: "/teams", color: "secondary" },
    { label: "Team Detail", path: "/teams/:teamId", color: "secondary" },
    { label: "User Teams", path: "/user-teams", color: "secondary" },
    { label: "Add Card", path: "/card/add", color: "secondary" },
    { label: "Subscribe Plan", path: "/plan/:planId/subscribe", color: "secondary" },
    { label: "Plan", path: "/plan", color: "secondary" },
    { label: "Edit User", path: "/user/edit", color: "secondary" },
    { label: "Edit Account", path: "/account/edit", color: "secondary" },
    { label: "Users", path: "/users", color: "secondary" },
    { label: "Create User", path: "/create-user", color: "secondary" },
    { label: "Edit User Detail", path: "/edit-user/:userId", color: "secondary" },
    { label: "User Detail", path: "/user/:userId", color: "secondary" }
  ];

  return (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
        backgroundColor: darkMode ? 'black' : 'white',
        background: 'transparent',
      }}
    >
      <Box
        sx={{
          width: {
            xs: '100%',
            sm: 600,
            md: 960,
            lg: 1280,
            xl: 1920,
          },
          paddingY: { xs: 2, sm: 4 },
        }}
      >
        <Grid container spacing={2}>
          {/* Column 1 - Public Routes */}
          <Grid item xs={6} sm={2}>
            <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
              <StyledButton onClick={handleMenuOpen('publicRoutes')}>
                Public
              </StyledButton>
              <Menu
                anchorEl={anchorEls.publicRoutes}
                open={Boolean(anchorEls.publicRoutes)}
                onClose={handleMenuClose('publicRoutes')}
              >
                {publicRoutes.map((item, index) => (
                  <MenuItem
                    key={index}
                    onClick={() => handleMenuItemClick(item.path, 'publicRoutes')}
                  >
                    {item.label}
                  </MenuItem>
                ))}
              </Menu>
            </Stack>
          </Grid>

          {/* Column 2 - Public APIs */}
          <Grid item xs={6} sm={2}>
            <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
              <StyledButton onClick={handleMenuOpen('publicAPIs')}>
                APIs
              </StyledButton>
              <Menu
                anchorEl={anchorEls.publicAPIs}
                open={Boolean(anchorEls.publicAPIs)}
                onClose={handleMenuClose('publicAPIs')}
              >
                {publicAPIs.map((item, index) => (
                  <MenuItem
                    key={index}
                    onClick={() => handleMenuItemClick(item.path, 'publicAPIs')}
                  >
                    {item.label}
                  </MenuItem>
                ))}
              </Menu>
            </Stack>
          </Grid>

          {/* Column 3 - Additional Public Routes */}
          <Grid item xs={6} sm={2}>
            <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
              <StyledButton onClick={handleMenuOpen('additionalPublicRoutes')}>
                Routes
              </StyledButton>
              <Menu
                anchorEl={anchorEls.additionalPublicRoutes}
                open={Boolean(anchorEls.additionalPublicRoutes)}
                onClose={handleMenuClose('additionalPublicRoutes')}
              >
                {additionalPublicRoutes.map((item, index) => (
                  <MenuItem
                    key={index}
                    onClick={() => handleMenuItemClick(item.path, 'additionalPublicRoutes')}
                  >
                    {item.label}
                  </MenuItem>
                ))}
              </Menu>
            </Stack>
          </Grid>

          {/* Column 4 - GitHub Links and Resources */}
          <Grid item xs={6} sm={2}>
            <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
              <StyledButton onClick={handleMenuOpen('githubLinksAndResources')}>
                GitHub
              </StyledButton>
              <Menu
                anchorEl={anchorEls.githubLinksAndResources}
                open={Boolean(anchorEls.githubLinksAndResources)}
                onClose={handleMenuClose('githubLinksAndResources')}
              >
                {githubLinksAndResources.map((item, index) => (
                  <MenuItem
                    key={index}
                    onClick={() => handleMenuItemClick(item.path, 'githubLinksAndResources')}
                  >
                    {item.icon && <span style={{ marginRight: '8px', display: 'inline-flex' }}>{item.icon}</span>}
                    {item.label}
                  </MenuItem>
                ))}
              </Menu>
            </Stack>
          </Grid>

          {/* Column 5 - Auth Routes */}
          {(user?.id || isAdmin) && (
            <Grid item xs={6} sm={2}>
              <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
                <StyledButton onClick={handleMenuOpen('authRoutes')}>
                  Auth
                </StyledButton>
                <Menu
                  anchorEl={anchorEls.authRoutes}
                  open={Boolean(anchorEls.authRoutes)}
                  onClose={handleMenuClose('authRoutes')}
                >
                  {authRoutes.map((item, index) => (
                    <MenuItem
                      key={index}
                      onClick={() => handleMenuItemClick(item.path, 'authRoutes')}
                    >
                      {item.label}
                    </MenuItem>
                  ))}
                </Menu>
              </Stack>
            </Grid>
          )}

          {/* Column 6 - Private Routes */}
          {(user?.id || isAdmin) && (
            <Grid item xs={6} sm={2}>
              <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
                <StyledButton onClick={handleMenuOpen('privateRoutes')}>
                  Private
                </StyledButton>
                <Menu
                  anchorEl={anchorEls.privateRoutes}
                  open={Boolean(anchorEls.privateRoutes)}
                  onClose={handleMenuClose('privateRoutes')}
                >
                  {privateRoutes.map((item, index) => (
                    <MenuItem
                      key={index}
                      onClick={() => handleMenuItemClick(item.path, 'privateRoutes')}
                    >
                      {item.label}
                    </MenuItem>
                  ))}
                </Menu>
              </Stack>
            </Grid>
          )}
        </Grid>
      </Box>
    </Box>
  );
};

export default Footer;